
import moment from 'moment';
/**
 * 下载文件
 * */
export const downLoad = {
    /**
     * res：返回的文件流
     * fileName： 文件名称
     * isAddTime 是否给文件添加时间，默认添加
     * type 下载文件的类型，如果是excel则可不传，zip时需要type='application/zip'
     * */
    downLoadFile: (res, fileName = 'template.xls', isAddTime = true, type = false) => {
        let data = new Blob([res.data]);
        if (type) {
            data = new Blob([res.data], {type: type});
        }
        let contentDisposition = res.headers ? res.headers['content-disposition'] : '';
        let renameFile = '';
        if (contentDisposition) {
            renameFile = contentDisposition.split('filename=')[1];
            renameFile = decodeURI(renameFile);
        }
        let currentTime = moment().format("YYYY-MM-DD");
        let index = fileName.lastIndexOf(".");
        //获取后缀
        let frontStr = fileName.substring(0, index);
        let lastStr = fileName.substring(index);
        if (isAddTime) {
            fileName = `${frontStr}${currentTime}${lastStr}`;
        } else {
            fileName=renameFile?renameFile:`${frontStr}${lastStr}`
        }
        if (window.navigator.msSaveOrOpenBlob) { // IE
            navigator.msSaveBlob(data, fileName)
        } else {
            // 通过a标签把内容下载到本地
            let obj = window.URL.createObjectURL(data);
            let a = document.createElement('a');
            a.download = fileName;
            a.href = obj;
            a.click();
            // 下载完毕，释放
            a.onload = function () {
                window.URL.revokeObjectURL(obj);
            };
        }
    },
    GetUrlDownFile(url, filename) {
        this.getBlob(url, function (blob) {
            this.saveAs(blob, filename);
        })
    },
    getBlob(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = function () {
            if (xhr.status === 200) {
                cb(xhr.response);
            }
        };
        xhr.send();
    },
    /**
     * 保存
     * @param  {Blob} blob
     * @param  {String} filename 想要保存的文件名称
     */
    saveAs(blob, filename) {
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement('a');
            var body = document.querySelector('body');

            link.href = window.URL.createObjectURL(blob);
            link.download = filename;

            // fix Firefox
            link.style.display = 'none';
            body.appendChild(link);

            link.click();
            body.removeChild(link);

            window.URL.revokeObjectURL(link.href);
        }
    }
}
